<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>单词记忆大师</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#4F46E5',
            secondary: '#EC4899',
            neutral: '#1F2937',
            success: '#10B981',
            danger: '#EF4444',
            warning: '#F59E0B',
            info: '#3B82F6',
            light: '#F9FAFB',
            dark: '#111827'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-flip {
        perspective: 1000px;
        transform-style: preserve-3d;
      }
      .card-front, .card-back {
        backface-visibility: hidden;
        transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
      }
      .card-back {
        transform: rotateY(180deg);
      }
      .card-flipped .card-front {
        transform: rotateY(180deg);
      }
      .card-flipped .card-back {
        transform: rotateY(0deg);
      }
      .progress-animation {
        transition: width 0.5s ease-in-out;
      }
      .btn-hover {
        transition: all 0.3s ease;
      }
      .btn-hover:hover {
        transform: translateY(-2px);
      }
      .text-shadow {
        text-shadow: 0 2px 4px rgba(0,0,0,0.1);
      }
      .card-hover {
        transition: all 0.3s ease;
      }
      .card-hover:hover {
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
      }
      .scale-hover {
        transition: transform 0.3s ease;
      }
      .scale-hover:hover {
        transform: scale(1.03);
      }
      .gradient-text {
        background-clip: text;
        -webkit-background-clip: text;
        color: transparent;
      }
      .calendar-day {
        transition: all 0.2s ease;
      }
      .calendar-day:hover:not(.today) {
        transform: scale(1.1);
      }
      .today {
        animation: pulse 2s infinite;
      }
      @keyframes pulse {
        0% {
          box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.4);
        }
        70% {
          box-shadow: 0 0 0 10px rgba(79, 70, 229, 0);
        }
        100% {
          box-shadow: 0 0 0 0 rgba(79, 70, 229, 0);
        }
      }
      .typing-animation {
        overflow: hidden;
        white-space: nowrap;
        animation: typing 2s steps(40, end);
      }
      @keyframes typing {
        from { width: 0 }
        to { width: 100% }
      }
      .fade-in {
        animation: fadeIn 0.5s ease-in-out;
      }
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }
      .slide-up {
        animation: slideUp 0.5s ease-out;
      }
      @keyframes slideUp {
        from { transform: translateY(20px); opacity: 0; }
        to { transform: translateY(0); opacity: 1; }
      }
    }
  </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen font-sans">
  <div class="container mx-auto px-4 py-8 max-w-5xl">
    <!-- 游戏标题 -->
    <header class="text-center mb-8">
      <h1 class="text-[clamp(2rem,5vw,3.5rem)] font-bold gradient-text bg-gradient-to-r from-primary to-secondary mb-2 text-shadow typing-animation">单词记忆大师</h1>
      <p class="text-gray-600 text-lg fade-in">通过趣味游戏提升你的词汇量</p>
    </header>

    <!-- 游戏状态和控制区 -->
    <div class="flex flex-col md:flex-row justify-between items-center mb-6 gap-4 slide-up">
      <div class="flex items-center gap-3">
        <div class="bg-white p-3 rounded-lg shadow-md flex items-center gap-2 card-hover">
          <i class="fa fa-book text-primary text-xl"></i>
          <span class="font-medium">单词总数: <span id="total-words" class="text-primary font-bold">0</span></span>
        </div>
        <div class="bg-white p-3 rounded-lg shadow-md flex items-center gap-2 card-hover">
          <i class="fa fa-check-circle text-success text-xl"></i>
          <span class="font-medium">已掌握: <span id="mastered-words" class="text-success font-bold">0</span></span>
        </div>
        <div class="bg-white p-3 rounded-lg shadow-md flex items-center gap-2 card-hover">
          <i class="fa fa-refresh text-warning text-xl"></i>
          <span class="font-medium">剩余: <span id="remaining-words" class="text-warning font-bold">0</span></span>
        </div>
      </div>
      
      <div class="flex gap-2">
        <button id="upload-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-upload"></i>
          <span>上传单词</span>
        </button>
        <button id="restart-btn" class="bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2" disabled>
          <i class="fa fa-refresh"></i>
          <span>重新开始</span>
        </button>
        <button id="settings-btn" class="bg-neutral hover:bg-neutral/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-cog"></i>
          <span>设置</span>
        </button>
        <button id="stats-btn" class="bg-info hover:bg-info/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-bar-chart"></i>
          <span>统计</span>
        </button>
        <button id="add-word-btn" class="bg-success hover:bg-success/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-plus"></i>
          <span>添加单词</span>
        </button>
      </div>
    </div>

    <!-- 添加单词面板 -->
    <div id="add-word-panel" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
      <div class="bg-white rounded-xl shadow-2xl p-6 max-w-md w-full mx-4 scale-hover">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-bold text-gray-800">添加新单词</h3>
          <button id="close-add-word-btn" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="space-y-4">
          <div>
            <label class="block text-gray-700 mb-2" for="new-word">单词</label>
            <input type="text" id="new-word" placeholder="输入单词" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
          <div>
            <label class="block text-gray-700 mb-2" for="new-meaning">释义</label>
            <input type="text" id="new-meaning" placeholder="输入释义" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
          <div>
            <label class="block text-gray-700 mb-2" for="new-pronunciation">发音 (可选)</label>
            <input type="text" id="new-pronunciation" placeholder="输入发音" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
          <div>
            <label class="block text-gray-700 mb-2" for="new-example">例句 (可选)</label>
            <input type="text" id="new-example" placeholder="输入例句" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
        </div>
        <div class="mt-6 flex justify-end">
          <button id="save-word-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg shadow-md btn-hover">
            <i class="fa fa-save mr-2"></i>保存单词
          </button>
        </div>
      </div>
    </div>

    <!-- 生成CSV面板 -->
    <div id="generate-csv-panel" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
      <div class="bg-white rounded-xl shadow-2xl p-6 max-w-md w-full mx-4 scale-hover">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-bold text-gray-800">生成CSV文件</h3>
          <button id="close-generate-csv-btn" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="space-y-4">
          <div>
            <label class="block text-gray-700 mb-2">选择要导出的单词</label>
            <div class="space-y-2">
              <label class="flex items-center">
                <input type="radio" name="export-type" value="all" checked class="mr-2">
                <span>所有单词</span>
              </label>
              <label class="flex items-center">
                <input type="radio" name="export-type" value="mastered" class="mr-2">
                <span>已掌握的单词</span>
              </label>
              <label class="flex items-center">
                <input type="radio" name="export-type" value="unmastered" class="mr-2">
                <span>未掌握的单词</span>
              </label>
            </div>
          </div>
          <div>
            <label class="block text-gray-700 mb-2" for="csv-filename">文件名</label>
            <input type="text" id="csv-filename" placeholder="输入文件名" value="vocabulary_list"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
        </div>
        <div class="mt-6 flex justify-end">
          <button id="download-csv-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg shadow-md btn-hover">
            <i class="fa fa-download mr-2"></i>下载CSV
          </button>
        </div>
      </div>
    </div>

    <!-- 设置面板 -->
    <div id="settings-panel" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
      <div class="bg-white rounded-xl shadow-2xl p-6 max-w-md w-full mx-4 scale-hover">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-bold text-gray-800">游戏设置</h3>
          <button id="close-settings-btn" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="space-y-4">
          <div>
            <label class="block text-gray-700 mb-2" for="card-flip-speed">卡片翻转速度</label>
            <input type="range" id="card-flip-speed" min="100" max="1000" step="100" value="600" 
                  class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
            <div class="flex justify-between text-xs text-gray-500 mt-1">
              <span>慢</span>
              <span>快</span>
            </div>
          </div>
          <div>
            <label class="block text-gray-700 mb-2">学习模式</label>
            <div class="space-y-2">
              <label class="flex items-center">
                <input type="radio" name="study-mode" value="all" checked class="mr-2">
                <span>全部单词</span>
              </label>
              <label class="flex items-center">
                <input type="radio" name="study-mode" value="mastered" class="mr-2">
                <span>只复习已掌握</span>
              </label>
              <label class="flex items-center">
                <input type="radio" name="study-mode" value="unmastered" class="mr-2">
                <span>只学习未掌握</span>
              </label>
              <label class="flex items-center">
                <input type="radio" name="study-mode" value="quiz" class="mr-2">
                <span>测试模式</span>
              </label>
            </div>
          </div>
          <div>
            <label class="block text-gray-700 mb-2" for="words-per-session">每轮学习单词数</label>
            <input type="number" id="words-per-session" min="5" max="100" value="20" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
          <div>
            <label class="block text-gray-700 mb-2">主题</label>
            <div class="flex gap-3">
              <button id="theme-light" class="flex-1 bg-white border-2 border-primary text-primary py-2 rounded-lg">
                <i class="fa fa-sun-o mr-1"></i> 浅色
              </button>
              <button id="theme-dark" class="flex-1 bg-neutral border-2 border-neutral text-white py-2 rounded-lg">
                <i class="fa fa-moon-o mr-1"></i> 深色
              </button>
            </div>
          </div>
        </div>
        <div class="mt-6 flex justify-end">
          <button id="save-settings-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg shadow-md btn-hover">
            保存设置
          </button>
        </div>
      </div>
    </div>

    <!-- 统计面板 -->
    <div id="stats-panel" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
      <div class="bg-white rounded-xl shadow-2xl p-6 max-w-3xl w-full mx-4 scale-hover max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-bold text-gray-800">学习统计</h3>
          <button id="close-stats-btn" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div class="bg-white rounded-xl shadow-md p-6 card-hover">
            <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
              <i class="fa fa-line-chart text-primary mr-2"></i>
              学习进度
            </h4>
            <div class="h-64">
              <canvas id="progress-chart"></canvas>
            </div>
          </div>
          
          <div class="bg-white rounded-xl shadow-md p-6 card-hover">
            <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
              <i class="fa fa-calendar-check-o text-success mr-2"></i>
              学习日历
            </h4>
            <div id="detailed-calendar" class="grid grid-cols-7 gap-1">
              <!-- 日历将由JS动态生成 -->
            </div>
          </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-md p-6 card-hover mb-6">
          <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
            <i class="fa fa-trophy text-warning mr-2"></i>
            学习成就
          </h4>
          <div id="achievements" class="grid grid-cols-2 md:grid-cols-4 gap-4">
            <!-- 成就将由JS动态生成 -->
          </div>
        </div>
        
        <div class="bg-white rounded-xl shadow-md p-6 card-hover">
          <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
            <i class="fa fa-book text-info mr-2"></i>
            单词掌握情况
          </h4>
          <div id="word-stats" class="space-y-4 max-h-64 overflow-y-auto">
            <!-- 单词统计将由JS动态生成 -->
          </div>
        </div>
      </div>
    </div>

    <!-- 文件上传区域 -->
    <div id="upload-area" class="mb-8 border-2 border-dashed border-gray-300 rounded-xl p-8 text-center bg-white/80 transition-all duration-300 hover:bg-white slide-up">
      <div class="max-w-md mx-auto">
        <i class="fa fa-cloud-upload text-5xl text-gray-400 mb-4"></i>
        <h2 class="text-xl font-semibold text-gray-700 mb-2">上传单词文件</h2>
        <p class="text-gray-500 mb-6">请上传CSV文件，每行格式为：单词,释义,发音[可选],例句[可选]</p>
        <input type="file" id="file-input" accept=".csv" class="hidden">
        <label for="file-input" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg shadow-md cursor-pointer inline-block btn-hover">
          <i class="fa fa-file-text-o mr-2"></i>选择CSV文件
        </label>
        <p id="file-name" class="mt-4 text-sm text-gray-500"></p>
        <div class="mt-6">
          <p class="text-gray-500 mb-2">或者使用示例单词</p>
          <button id="use-sample-btn" class="bg-info hover:bg-info/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover">
            <i class="fa fa-lightbulb-o mr-2"></i>使用示例单词
          </button>
          <button id="generate-sample-csv-btn" class="bg-success hover:bg-success/90 text-white px-4 py-2 rounded-lg shadow-md btn-hover mt-2">
            <i class="fa fa-file-text-o mr-2"></i>下载示例CSV
          </button>
        </div>
      </div>
    </div>

    <!-- 游戏主区域 -->
    <div id="game-area" class="hidden">
      <!-- 进度条 -->
      <div class="mb-6 slide-up">
        <div class="flex justify-between text-sm mb-1">
          <span class="font-medium">学习进度</span>
          <span id="progress-text" class="text-primary font-bold">0%</span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-2.5">
          <div id="progress-bar" class="bg-primary h-2.5 rounded-full progress-animation" style="width: 0%"></div>
        </div>
      </div>

      <!-- 单词卡片 -->
      <div id="word-card" class="card-flip relative w-full max-w-md mx-auto h-[300px] mb-8 cursor-pointer">
        <div class="card-front absolute w-full h-full bg-white rounded-2xl shadow-xl flex flex-col items-center justify-center p-8">
          <h3 class="text-3xl font-bold text-neutral mb-4" id="current-word">Word</h3>
          <div class="flex items-center text-gray-500 mb-6">
            <button id="pronounce-btn" class="text-gray-500 hover:text-primary transition-colors">
              <i class="fa fa-volume-up mr-2 text-xl"></i>
            </button>
            <span id="word-pronunciation">[prəˌnʌnsiˈeɪʃn]</span>
          </div>
          <p class="text-sm text-gray-400">点击卡片查看释义</p>
        </div>
        <div class="card-back absolute w-full h-full bg-white rounded-2xl shadow-xl flex flex-col items-center justify-center p-8">
          <h3 class="text-xl font-semibold text-gray-700 mb-2">释义</h3>
          <p class="text-2xl font-medium text-neutral text-center mb-6" id="word-meaning">Meaning</p>
          <div class="flex items-center text-gray-500 mb-4">
            <i class="fa fa-sentence mr-2"></i>
            <span id="word-example">Example sentence...</span>
          </div>
          <div class="flex items-center text-gray-500">
            <i class="fa fa-exchange mr-2"></i>
            <span>点击卡片返回单词</span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-center gap-4 mb-8">
        <button id="know-btn" class="bg-success hover:bg-success/90 text-white px-8 py-3 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-check-circle"></i>
          <span>已掌握</span>
        </button>
        <button id="next-btn" class="bg-warning hover:bg-warning/90 text-white px-8 py-3 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-arrow-right"></i>
          <span>下一个</span>
        </button>
        <button id="dont-know-btn" class="bg-danger hover:bg-danger/90 text-white px-8 py-3 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-times-circle"></i>
          <span>未掌握</span>
        </button>
      </div>

      <!-- 测试模式选项 (仅在测试模式下显示) -->
      <div id="quiz-options" class="hidden max-w-md mx-auto mb-8">
        <div id="quiz-choices" class="space-y-3">
          <!-- 选项将由JS动态生成 -->
        </div>
      </div>

      <!-- 学习记录 -->
      <div class="bg-white/80 rounded-xl shadow-md p-6 mb-8">
        <h3 class="text-xl font-semibold text-gray-700 mb-4 flex items-center">
          <i class="fa fa-history text-primary mr-2"></i>
          最近学习记录
        </h3>
        <div id="history-list" class="space-y-3 max-h-40 overflow-y-auto pr-2">
          <div class="text-center text-gray-500 italic">暂无记录</div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
        <div class="bg-white/80 rounded-xl shadow-md p-6 card-hover">
          <h3 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
            <i class="fa fa-bar-chart text-info mr-2"></i>
            学习统计
          </h3>
          <div class="space-y-3">
            <div class="flex justify-between items-center">
              <span class="text-gray-600">今日学习</span>
              <span class="font-bold text-primary" id="today-stats">0 个单词</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-gray-600">连续学习</span>
              <span class="font-bold text-secondary" id="streak-stats">0 天</span>
            </div>
            <div class="flex justify-between items-center">
              <span class="text-gray-600">总学习量</span>
              <span class="font-bold text-warning" id="total-stats">0 个单词</span>
            </div>
          </div>
        </div>
        
        <div class="bg-white/80 rounded-xl shadow-md p-6 card-hover">
          <h3 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
            <i class="fa fa-calendar text-success mr-2"></i>
            学习日历
          </h3>
          <div id="calendar-container" class="text-center">
            <p class="text-gray-500 italic">暂无数据</p>
          </div>
        </div>
      </div>

      <!-- 导出选项 -->
      <div class="flex justify-center gap-4 mb-8">
        <button id="export-all-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-download mr-2"></i>导出所有单词
        </button>
        <button id="export-mastered-btn" class="bg-success hover:bg-success/90 text-white px-6 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-check-circle mr-2"></i>导出已掌握
        </button>
        <button id="export-unmastered-btn" class="bg-danger hover:bg-danger/90 text-white px-6 py-2 rounded-lg shadow-md btn-hover flex items-center gap-2">
          <i class="fa fa-times-circle mr-2"></i>导出未掌握
        </button>
      </div>
    </div>

    <!-- 学习完成提示 -->
    <div id="completion-message" class="hidden text-center p-12 bg-white/80 rounded-2xl shadow-xl">
      <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-success/20 mb-6">
        <i class="fa fa-trophy text-3xl text-success"></i>
      </div>
      <h2 class="text-2xl font-bold text-gray-800 mb-2">恭喜你！</h2>
      <p class="text-gray-600 mb-6">你已经完成了所有单词的学习</p>
      <div class="mb-6">
        <div class="flex justify-center gap-4">
          <div class="text-center">
            <div class="text-3xl font-bold text-primary" id="completion-total">0</div>
            <div class="text-sm text-gray-500">总单词数</div>
          </div>
          <div class="text-center">
            <div class="text-3xl font-bold text-success" id="completion-mastered">0</div>
            <div class="text-sm text-gray-500">已掌握</div>
          </div>
          <div class="text-center">
            <div class="text-3xl font-bold text-warning" id="completion-time">0</div>
            <div class="text-sm text-gray-500">学习时间(分钟)</div>
          </div>
        </div>
      </div>
      <div class="flex justify-center gap-4">
        <button id="restart-after-complete-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg shadow-md btn-hover">
          <i class="fa fa-refresh mr-2"></i>重新开始学习
        </button>
        <button id="export-all-after-complete-btn" class="bg-info hover:bg-info/90 text-white px-6 py-3 rounded-lg shadow-md btn-hover">
          <i class="fa fa-download mr-2"></i>导出所有单词
        </button>
      </div>
    </div>

    <!-- 页脚 -->
    <footer class="text-center text-gray-500 mt-12 text-sm">
      <p>单词记忆大师 © 2025 | 通过游戏化学习提升你的词汇量</p>
    </footer>
  </div>

  <script>
    // 全局变量
    let words = [];
    let currentWordIndex = 0;
    let masteredWords = [];
    let history = [];
    let shuffledIndices = [];
    let settings = {
      cardFlipSpeed: 600,
      studyMode: 'all',
      wordsPerSession: 20,
      theme: 'light'
    };
    let studySession = {
      startTime: null,
      wordsStudied: 0,
      totalTime: 0
    };
    let statistics = {
      todayWords: 0,
      streak: 0,
      totalWords: 0,
      calendar: {},
      achievements: {}
    };
    let quizOptions = []; // 测试模式选项

    // DOM 元素
    const uploadArea = document.getElementById('upload-area');
    const gameArea = document.getElementById('game-area');
    const completionMessage = document.getElementById('completion-message');
    const fileInput = document.getElementById('file-input');
    const fileName = document.getElementById('file-name');
    const uploadBtn = document.getElementById('upload-btn');
    const restartBtn = document.getElementById('restart-btn');
    const restartAfterCompleteBtn = document.getElementById('restart-after-complete-btn');
    const wordCard = document.getElementById('word-card');
    const currentWord = document.getElementById('current-word');
    const wordPronunciation = document.getElementById('word-pronunciation');
    const wordMeaning = document.getElementById('word-meaning');
    const wordExample = document.getElementById('word-example');
    const knowBtn = document.getElementById('know-btn');
    const nextBtn = document.getElementById('next-btn');
    const dontKnowBtn = document.getElementById('dont-know-btn');
    const totalWordsElement = document.getElementById('total-words');
    const masteredWordsElement = document.getElementById('mastered-words');
    const remainingWordsElement = document.getElementById('remaining-words');
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    const historyList = document.getElementById('history-list');
    const settingsBtn = document.getElementById('settings-btn');
    const settingsPanel = document.getElementById('settings-panel');
    const closeSettingsBtn = document.getElementById('close-settings-btn');
    const saveSettingsBtn = document.getElementById('save-settings-btn');
    const cardFlipSpeed = document.getElementById('card-flip-speed');
    const studyMode = document.getElementsByName('study-mode');
    const wordsPerSession = document.getElementById('words-per-session');
    const pronounceBtn = document.getElementById('pronounce-btn');
    const useSampleBtn = document.getElementById('use-sample-btn');
    const todayStats = document.getElementById('today-stats');
    const streakStats = document.getElementById('streak-stats');
    const totalStats = document.getElementById('total-stats');
        // 发音功能
    pronounceBtn.addEventListener('click', () => {
      if ('speechSynthesis' in window && currentWord.textContent) {
        const utterance = new SpeechSynthesisUtterance(currentWord.textContent);
        utterance.lang = 'en-US';
        window.speechSynthesis.speak(utterance);
      }
    });

    // 卡片翻转
    wordCard.addEventListener('click', () => {
      wordCard.classList.toggle('card-flipped');
    });

    // 上传文件处理
    fileInput.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (file) {
        fileName.textContent = file.name;
        const reader = new FileReader();
        reader.onload = (event) => {
          try {
            const content = event.target.result;
            parseCsv(content);
            startGame();
          } catch (error) {
            alert('解析CSV文件时出错: ' + error.message);
          }
        };
        reader.readAsText(file);
      }
    });

    // 解析CSV文件
    function parseCsv(content) {
      const lines = content.split('\n');
      words = [];
      
      for (let i = 0; i < lines.length; i++) {
        if (lines[i].trim() === '') continue;
        
        // 处理引号内的逗号
        const regex = /(?:")([^"]*)(?:")|([^,]*)/g;
        const matches = [];
        let match;
        
        while ((match = regex.exec(lines[i])) !== null) {
          if (match[1] !== undefined) {
            matches.push(match[1]);
          } else if (match[2] !== undefined) {
            matches.push(match[2].trim());
          }
        }
        
        // 过滤空匹配
        const values = matches.filter(value => value !== '');
        
        if (values.length >= 2) {
          words.push({
            word: values[0],
            meaning: values[1],
            pronunciation: values.length > 2 ? values[2] : '',
            example: values.length > 3 ? values[3] : '',
            mastered: false
          });
        }
      }
      
      updateWordCount();
    }

    // 更新单词计数
    function updateWordCount() {
      totalWordsElement.textContent = words.length;
      masteredWordsElement.textContent = masteredWords.length;
      remainingWordsElement.textContent = words.length - masteredWords.length;
      
      const progress = Math.round((masteredWords.length / words.length) * 100);
      progressBar.style.width = `${progress}%`;
      progressText.textContent = `${progress}%`;
    }

    // 开始游戏
    function startGame() {
      if (words.length === 0) {
        alert('请先上传单词文件或使用示例单词');
        return;
      }
      
      // 开始计时
      studySession.startTime = new Date();
      
      // 重置学习记录
      history = [];
      updateHistoryList();
      
      // 随机打乱单词顺序
      shuffledIndices = Array.from({length: words.length}, (_, i) => i);
      shuffleArray(shuffledIndices);
      
      // 显示游戏区域
      uploadArea.classList.add('hidden');
      gameArea.classList.remove('hidden');
      completionMessage.classList.add('hidden');
      
      // 启用重启按钮
      restartBtn.disabled = false;
      
      // 显示第一个单词
      currentWordIndex = 0;
      displayCurrentWord();
      
      // 更新统计信息
      updateStats();
    }

    // 随机打乱数组
    function shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
    }

    // 显示当前单词
    function displayCurrentWord() {
      if (currentWordIndex >= shuffledIndices.length) {
        finishGame();
        return;
      }
      
      const wordIndex = shuffledIndices[currentWordIndex];
      const word = words[wordIndex];
      
      currentWord.textContent = word.word;
      wordPronunciation.textContent = word.pronunciation || `[${word.word}]`;
      wordMeaning.textContent = word.meaning;
      wordExample.textContent = word.example || 'No example provided';
      
      // 重置卡片状态
      wordCard.classList.remove('card-flipped');
      
      // 测试模式下生成选项
      if (settings.studyMode === 'quiz') {
        generateQuizOptions(wordIndex);
      } else {
        document.getElementById('quiz-options').classList.add('hidden');
      }
    }

    // 生成测试模式选项
    function generateQuizOptions(correctIndex) {
      const quizChoices = document.getElementById('quiz-choices');
      quizChoices.innerHTML = '';
      
      // 获取当前单词的正确释义
      const correctMeaning = words[correctIndex].meaning;
      
      // 创建选项数组（包括正确答案和3个干扰项）
      quizOptions = [correctMeaning];
      
      // 随机选择3个其他单词的释义作为干扰项
      const otherIndices = [];
      for (let i = 0; i < words.length; i++) {
        if (i !== correctIndex) {
          otherIndices.push(i);
        }
      }
      
      shuffleArray(otherIndices);
      
      for (let i = 0; i < 3 && i < otherIndices.length; i++) {
        quizOptions.push(words[otherIndices[i]].meaning);
      }
      
      // 打乱选项顺序
      shuffleArray(quizOptions);
      
      // 创建选项按钮
      quizOptions.forEach((option, index) => {
        const button = document.createElement('button');
        button.className = 'w-full bg-white hover:bg-gray-50 text-left px-4 py-3 rounded-lg shadow border border-gray-200 transition-all duration-200 flex items-center';
        
        // 添加选项字母标识
        const letterSpan = document.createElement('span');
        letterSpan.className = 'w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center mr-3 font-bold';
        letterSpan.textContent = String.fromCharCode(65 + index); // A, B, C, D
        button.appendChild(letterSpan);
        
        // 添加选项文本
        const textSpan = document.createElement('span');
        textSpan.textContent = option;
        button.appendChild(textSpan);
        
        // 添加点击事件
        button.addEventListener('click', () => {
          checkQuizAnswer(button, option === correctMeaning);
        });
        
        quizChoices.appendChild(button);
      });
      
      // 显示选项区域
      document.getElementById('quiz-options').classList.remove('hidden');
    }

    // 检查测试答案
    function checkQuizAnswer(button, isCorrect) {
      // 禁用所有选项按钮
      const options = document.querySelectorAll('#quiz-choices button');
      options.forEach(btn => {
        btn.disabled = true;
        if (btn !== button) {
          btn.classList.add('opacity-50');
        }
      });
      
      // 显示正确/错误状态
      if (isCorrect) {
        button.classList.add('bg-success/20', 'border-success', 'text-success');
        setTimeout(() => {
          markWordAsMastered(true);
        }, 1000);
      } else {
        button.classList.add('bg-danger/20', 'border-danger', 'text-danger');
        
        // 高亮显示正确答案
        options.forEach(btn => {
          if (btn.textContent.includes(words[shuffledIndices[currentWordIndex]].meaning)) {
            btn.classList.add('bg-success/20', 'border-success', 'text-success');
          }
        });
        
        setTimeout(() => {
          markWordAsMastered(false);
        }, 2000);
      }
    }

    // 标记单词为已掌握/未掌握
    function markWordAsMastered(isMastered) {
      const wordIndex = shuffledIndices[currentWordIndex];
      words[wordIndex].mastered = isMastered;
      
      // 添加到学习历史
      history.unshift({
        word: words[wordIndex].word,
        result: isMastered ? 'success' : 'fail',
        timestamp: new Date()
      });
      
      // 限制历史记录长度
      if (history.length > 10) {
        history.pop();
      }
      
      updateHistoryList();
      
      // 更新统计
      if (isMastered && !masteredWords.includes(wordIndex)) {
        masteredWords.push(wordIndex);
        updateWordCount();
      }
      
      // 移动到下一个单词
      currentWordIndex++;
      
      // 如果达到会话限制或没有更多单词，结束游戏
      if (currentWordIndex >= shuffledIndices.length || 
          (settings.wordsPerSession > 0 && currentWordIndex >= settings.wordsPerSession)) {
        finishGame();
        return;
      }
      
      // 显示下一个单词
      displayCurrentWord();
    }

    // 更新学习历史列表
    function updateHistoryList() {
      historyList.innerHTML = '';
      
      if (history.length === 0) {
        historyList.innerHTML = '<div class="text-center text-gray-500 italic">暂无记录</div>';
        return;
      }
      
      history.forEach(item => {
        const historyItem = document.createElement('div');
        historyItem.className = `flex items-center p-2 rounded-lg ${item.result === 'success' ? 'bg-success/10' : 'bg-danger/10'}`;
        
        // 添加图标
        const iconSpan = document.createElement('span');
        iconSpan.className = `w-6 h-6 rounded-full flex items-center justify-center mr-3 ${item.result === 'success' ? 'bg-success text-white' : 'bg-danger text-white'}`;
        iconSpan.innerHTML = item.result === 'success' ? '<i class="fa fa-check"></i>' : '<i class="fa fa-times"></i>';
        historyItem.appendChild(iconSpan);
        
        // 添加单词
        const wordSpan = document.createElement('span');
        wordSpan.className = 'font-medium';
        wordSpan.textContent = item.word;
        historyItem.appendChild(wordSpan);
        
        // 添加时间
        const timeSpan = document.createElement('span');
        timeSpan.className = 'ml-auto text-xs text-gray-500';
        const time = new Date(item.timestamp);
        timeSpan.textContent = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
        historyItem.appendChild(timeSpan);
        
        historyList.appendChild(historyItem);
      });
    }

    // 结束游戏
    function finishGame() {
      // 停止计时
      const endTime = new Date();
      studySession.totalTime = Math.round((endTime - studySession.startTime) / 60000); // 分钟
      
      // 更新统计
      updateStats();
      
      // 隐藏游戏区域，显示完成消息
      gameArea.classList.add('hidden');
      completionMessage.classList.remove('hidden');
      
      // 更新完成消息
      document.getElementById('completion-total').textContent = words.length;
      document.getElementById('completion-mastered').textContent = masteredWords.length;
      document.getElementById('completion-time').textContent = studySession.totalTime;
      
      // 更新学习日历
      updateCalendar();
    }

    // 下一个单词按钮
    nextBtn.addEventListener('click', () => {
      // 移动到下一个单词
      currentWordIndex++;
      
      if (currentWordIndex >= shuffledIndices.length) {
        finishGame();
        return;
      }
      
      displayCurrentWord();
    });

    // 已掌握按钮
    knowBtn.addEventListener('click', () => {
      markWordAsMastered(true);
    });

    // 未掌握按钮
    dontKnowBtn.addEventListener('click', () => {
      markWordAsMastered(false);
    });

    // 重新开始按钮
    restartBtn.addEventListener('click', () => {
      startGame();
    });

    // 完成后重新开始按钮
    restartAfterCompleteBtn.addEventListener('click', () => {
      startGame();
    });

    // 设置面板控制
    settingsBtn.addEventListener('click', () => {
      // 填充当前设置值
      cardFlipSpeed.value = settings.cardFlipSpeed;
      
      for (let i = 0; i < studyMode.length; i++) {
        if (studyMode[i].value === settings.studyMode) {
          studyMode[i].checked = true;
          break;
        }
      }
      
      wordsPerSession.value = settings.wordsPerSession;
      
      settingsPanel.classList.remove('hidden');
    });

    closeSettingsBtn.addEventListener('click', () => {
      settingsPanel.classList.add('hidden');
    });

    saveSettingsBtn.addEventListener('click', () => {
      // 保存设置
      settings.cardFlipSpeed = parseInt(cardFlipSpeed.value);
      settings.wordsPerSession = parseInt(wordsPerSession.value);
      
      for (let i = 0; i < studyMode.length; i++) {
        if (studyMode[i].checked) {
          settings.studyMode = studyMode[i].value;
          break;
        }
      }
      
      // 更新卡片翻转速度
      document.documentElement.style.setProperty('--card-flip-speed', `${settings.cardFlipSpeed}ms`);
      
      settingsPanel.classList.add('hidden');
      alert('设置已保存！');
    });

    // 使用示例单词
    useSampleBtn.addEventListener('click', () => {
      const sampleWords = [
        {word: "aberration", meaning: "偏差，脱离常轨", pronunciation: "[ˌæbəˈreɪʃn]", example: "His behavior was an aberration from his usual self."},
        {word: "abjure", meaning: "发誓放弃，宣誓弃绝", pronunciation: "[əbˈdʒʊr]", example: "He abjured his old beliefs."},
        {word: "ablution", meaning: "沐浴，净身", pronunciation: "[əˈbluːʃn]", example: "Muslims perform ablutions before prayer."},
        {word: "abnegation", meaning: "放弃，克制", pronunciation: "[ˌæbnɪˈɡeɪʃn]", example: "Her abnegation of personal desires impressed everyone."},
        {word: "abominate", meaning: "痛恨，憎恶", pronunciation: "[əˈbɑːmɪneɪt]", example: "I abominate cruelty to animals."},
        {word: "aboriginal", meaning: "土著的，原始的", pronunciation: "[ˌæbəˈrɪdʒənl]", example: "Aboriginal art has a long history."},
        {word: "abortive", meaning: "失败的，流产的", pronunciation: "[əˈbɔːrtɪv]", example: "The abortive attempt was a waste of resources."},
        {word: "abrade", meaning: "磨损，擦伤", pronunciation: "[əˈbreɪd]", example: "The rock surface was abraded by the wind."},
        {word: "abrogate", meaning: "废除，取消", pronunciation: "[ˈæbrəɡeɪt]", example: "The law was abrogated due to public opposition."},
        {word: "abstemious", meaning: "节制的，节俭的", pronunciation: "[əbˈstiːmiəs]", example: "He led an abstemious lifestyle."},
        {word: "abstruse", meaning: "深奥的，难懂的", pronunciation: "[əbˈstruːs]", example: "The professor's lecture was abstruse."},
        {word: "accede", meaning: "同意，就任", pronunciation: "[ækˈsiːd]", example: "The king acceded to the throne."},
        {word: "accolade", meaning: "荣誉，赞扬", pronunciation: "[ˈækəleɪd]", example: "The film received many accolades."},
        {word: "accrete", meaning: "积累，生长", pronunciation: "[əˈkriːt]", example: "Layers of sediment accreted over time."},
        {word: "acerbic", meaning: "尖刻的，酸的", pronunciation: "[əˈsɜːrbɪk]", example: "She gave an acerbic critique of the proposal."},
        {word: "acquiesce", meaning: "默许，顺从", pronunciation: "[ˌækwɪˈes]", example: "He acquiesced to their demands."},
        {word: "acrid", meaning: "辛辣的，刺鼻的", pronunciation: "[ˈækrɪd]", example: "The acrid smoke filled the room."},
        {word: "acrimonious", meaning: "尖刻的，激烈的", pronunciation: "[ˌækrɪˈməʊniəs]", example: "They had an acrimonious debate."},
        {word: "acumen", meaning: "敏锐，精明", pronunciation: "[ˈækjəmən]", example: "His business acumen made him successful."},
        {word: "adamant", meaning: "固执的，坚定的", pronunciation: "[ˈædəmənt]", example: "She was adamant about her decision."}
      ];
      
      words = sampleWords;
      masteredWords = [];
      updateWordCount();
      startGame();
    });

    // 生成示例CSV文件
    document.getElementById('generate-sample-csv-btn').addEventListener('click', () => {
      const sampleWords = [
        "aberration,偏差，脱离常轨,[ˌæbəˈreɪʃn],His behavior was an aberration from his usual self.",
        "abjure,发誓放弃，宣誓弃绝,[əbˈdʒʊr],He abjured his old beliefs.",
        "ablution,沐浴，净身,[əˈbluːʃn],Muslims perform ablutions before prayer.",
        "abnegation,放弃，克制,[ˌæbnɪˈɡeɪʃn],Her abnegation of personal desires impressed everyone.",
        "abominate,痛恨，憎恶,[əˈbɑːmɪneɪt],I abominate cruelty to animals.",
        "aboriginal,土著的，原始的,[ˌæbəˈrɪdʒənl],Aboriginal art has a long history.",
        "abortive,失败的，流产的,[əˈbɔːrtɪv],The abortive attempt was a waste of resources.",
        "abrade,磨损，擦伤,[əˈbreɪd],The rock surface was abraded by the wind.",
        "abrogate,废除，取消,[ˈæbrəɡeɪt],The law was abrogated due to public opposition.",
        "abstemious,节制的，节俭的,[əbˈstiːmiəs],He led an abstemious lifestyle."
      ];
      
      const csvContent = "单词,释义,发音,例句\n" + sampleWords.join("\n");
      downloadCsv(csvContent, "sample_vocabulary.csv");
    });

    // 下载CSV文件
    function downloadCsv(content, fileName) {
      const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', fileName);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    // 添加新单词
    document.getElementById('add-word-btn').addEventListener('click', () => {
      document.getElementById('add-word-panel').classList.remove('hidden');
    });

    document.getElementById('close-add-word-btn').addEventListener('click', () => {
      document.getElementById('add-word-panel').classList.add('hidden');
    });

    document.getElementById('save-word-btn').addEventListener('click', () => {
      const word = document.getElementById('new-word').value.trim();
      const meaning = document.getElementById('new-meaning').value.trim();
      const pronunciation = document.getElementById('new-pronunciation').value.trim();
      const example = document.getElementById('new-example').value.trim();
      
      if (!word || !meaning) {
        alert('单词和释义不能为空');
        return;
      }
      
      // 添加新单词
      words.push({
        word,
        meaning,
        pronunciation: pronunciation || `[${word}]`,
        example: example || '',
        mastered: false
      });
      
      // 重置表单
      document.getElementById('new-word').value = '';
      document.getElementById('new-meaning').value = '';
      document.getElementById('new-pronunciation').value = '';
      document.getElementById('new-example').value = '';
      
      // 关闭面板
      document.getElementById('add-word-panel').classList.add('hidden');
      
      // 更新单词计数
      updateWordCount();
      
      // 如果游戏已开始，重新开始以包含新单词
      if (gameArea.classList.contains('hidden') === false) {
        startGame();
      }
      
      alert('单词已添加成功！');
    });

    // 导出CSV功能
    document.getElementById('export-all-btn').addEventListener('click', () => {
      exportCsv('all');
    });

    document.getElementById('export-mastered-btn').addEventListener('click', () => {
      exportCsv('mastered');
    });

    document.getElementById('export-unmastered-btn').addEventListener('click', () => {
      exportCsv('unmastered');
    });

    document.getElementById('export-all-after-complete-btn').addEventListener('click', () => {
      exportCsv('all');
    });

    // 生成CSV面板
    document.getElementById('download-csv-btn').addEventListener('click', () => {
      const exportType = document.querySelector('input[name="export-type"]:checked').value;
      const fileName = document.getElementById('csv-filename').value.trim() || 'vocabulary_list';
      
      exportCsv(exportType, `${fileName}.csv`);
      document.getElementById('generate-csv-panel').classList.add('hidden');
    });

    document.getElementById('close-generate-csv-btn').addEventListener('click', () => {
      document.getElementById('generate-csv-panel').classList.add('hidden');
    });

    // 导出CSV
    function exportCsv(type, fileName = 'vocabulary.csv') {
      let exportWords = [];
      
      switch (type) {
        case 'all':
          exportWords = words;
          break;
        case 'mastered':
          exportWords = words.filter(word => word.mastered);
          break;
        case 'unmastered':
          exportWords = words.filter(word => !word.mastered);
          break;
      }
      
      if (exportWords.length === 0) {
        alert('没有可导出的单词');
        return;
      }
      
      // 构建CSV内容
      let csvContent = "单词,释义,发音,例句\n";
      
      exportWords.forEach(word => {
        // 处理可能包含逗号的字段
        const wordValue = escapeCsvValue(word.word);
        const meaningValue = escapeCsvValue(word.meaning);
        const pronunciationValue = escapeCsvValue(word.pronunciation);
        const exampleValue = escapeCsvValue(word.example);
        
        csvContent += `${wordValue},${meaningValue},${pronunciationValue},${exampleValue}\n`;
      });
      
      downloadCsv(csvContent, fileName);
    }

    // 转义CSV值
    function escapeCsvValue(value) {
      if (!value) return '';
      
      // 如果值包含逗号、双引号或换行符，则用双引号括起来
      if (value.includes(',') || value.includes('"') || value.includes('\n')) {
        // 替换双引号为两个双引号
        value = value.replace(/"/g, '""');
        return `"${value}"`;
      }
      
      return value;
    }

    // 统计面板
    document.getElementById('stats-btn').addEventListener('click', () => {
      updateStatsPanel();
      document.getElementById('stats-panel').classList.remove('hidden');
    });

    document.getElementById('close-stats-btn').addEventListener('click', () => {
      document.getElementById('stats-panel').classList.add('hidden');
    });

    // 更新统计面板
    function updateStatsPanel() {
      // 更新学习进度图表
      updateProgressChart();
      
      // 更新日历
      updateDetailedCalendar();
      
      // 更新成就
      updateAchievements();
      
      // 更新单词统计
      updateWordStats();
    }

    // 更新学习进度图表
    function updateProgressChart() {
      const ctx = document.getElementById('progress-chart').getContext('2d');
      
      // 销毁已存在的图表
      if (window.progressChartInstance) {
        window.progressChartInstance.destroy();
      }
      
      // 准备数据
      const labels = [];
      const data = [];
      const today = new Date();
      
      // 获取最近7天的数据
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(today.getDate() - i);
        const dateStr = date.toISOString().split('T')[0];
        
        labels.push(date.getDate());
        data.push(statistics.calendar[dateStr] || 0);
      }
      
      // 创建图表
      window.progressChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: '每日学习单词数',
            data: data,
            backgroundColor: 'rgba(79, 70, 229, 0.5)',
            borderColor: 'rgba(79, 70, 229, 1)',
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                precision: 0
              }
            }
          }
        }
      });
    }

    // 更新详细日历
    function updateDetailedCalendar() {
      const calendarContainer = document.getElementById('detailed-calendar');
      calendarContainer.innerHTML = '';
      
      // 添加星期标题
      const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
      weekdays.forEach(day => {
        const dayElement = document.createElement('div');
        dayElement.className = 'text-center font-medium text-gray-500 py-2';
        dayElement.textContent = day;
        calendarContainer.appendChild(dayElement);
      });
      
      // 获取当前月份
      const today = new Date();
      const currentMonth = today.getMonth();
      const currentYear = today.getFullYear();
      
      // 获取当月第一天是星期几
      const firstDay = new Date(currentYear, currentMonth, 1).getDay();
      
      // 获取当月的天数
      const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
      
      // 添加上个月的填充天数
      for (let i = 0; i < firstDay; i++) {
        const emptyDay = document.createElement('div');
        emptyDay.className = 'text-center py-2 text-gray-300';
        calendarContainer.appendChild(emptyDay);
      }
      
      // 添加当月的天数
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(currentYear, currentMonth, day);
        const dateStr = date.toISOString().split('T')[0];
        
        const dayElement = document.createElement('div');
        dayElement.className = 'text-center py-2 cursor-pointer calendar-day';
        
        // 今天的样式
        if (date.getDate() === today.getDate() && 
            date.getMonth() === today.getMonth() && 
            date.getFullYear() === today.getFullYear()) {
          dayElement.classList.add('today', 'bg-primary', 'text-white', 'rounded-full', 'font-bold');
        } else {
          // 根据学习量设置不同的背景色
          const studyCount = statistics.calendar[dateStr] || 0;
          
          if (studyCount > 0) {
            dayElement.classList.add('bg-primary/10', 'hover:bg-primary/20', 'rounded-full');
          }
          
          if (studyCount >= 10) {
            dayElement.classList.add('font-bold');
          }
        }
        
        dayElement.textContent = day;
        
        // 添加点击事件显示当天学习情况
        dayElement.addEventListener('click', () => {
          alert(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 学习了 ${statistics.calendar[dateStr] || 0} 个单词`);
        });
        
        calendarContainer.appendChild(dayElement);
      }
    }

    // 更新成就
    function updateAchievements() {
      const achievementsContainer = document.getElementById('achievements');
      achievementsContainer.innerHTML = '';
      
      // 定义成就列表
      const achievements = [
        {
          id: 'first_word',
          name: '初窥门径',
          description: '学习了第一个单词',
          icon: 'fa-book',
          color: 'text-primary',
          achieved: words.length > 0
        },
        {
          id: 'master_10',
          name: '单词达人',
          description: '掌握了10个单词',
          icon: 'fa-trophy',
          color: 'text-warning',
          achieved: masteredWords.length >= 10
        },
        {
          id: 'study_5_days',
          name: '坚持之星',
          description: '连续学习5天',
          icon: 'fa-calendar-check-o',
          color: 'text-success',
          achieved: statistics.streak >= 5
        },
        {
          id: 'quiz_perfect',
          name: '完美测试',
          description: '在测试模式中获得满分',
          icon: 'fa-check-circle',
          color: 'text-success',
          achieved: false // 实现逻辑可以在测试完成时更新
        },
        {
          id: 'study_30_min',
          name: '专注学习者',
          description: '单次学习30分钟以上',
          icon: 'fa-clock-o',
          color: 'text-info',
          achieved: studySession.totalTime >= 30
        },
        {
          id: 'add_word',
          name: '词汇贡献者',
          description: '添加了自定义单词',
          icon: 'fa-plus-circle',
          color: 'text-primary',
          achieved: false // 实现逻辑可以在添加单词时更新
        },
        {
          id: 'export_csv',
          name: '数据管理师',
          description: '导出了CSV文件',
          icon: 'fa-download',
          color: 'text-secondary',
          achieved: false // 实现逻辑可以在导出时更新
        },
        {
          id: 'master_all',
          name: '词汇大师',
          description: '掌握了所有单词',
          icon: 'fa-crown',
          color: 'text-warning',
          achieved: masteredWords.length === words.length && words.length > 0
        }
      ];
      
      // 渲染成就
      achievements.forEach(achievement => {
        const achievementCard = document.createElement('div');
        achievementCard.className = `p-4 rounded-lg shadow ${achievement.achieved ? 'bg-white' : 'bg-gray-100'}`;
        
        const iconContainer = document.createElement('div');
        iconContainer.className = `w-12 h-12 rounded-full flex items-center justify-center mx-auto mb-3 ${achievement.achieved ? 'bg-primary/10' : 'bg-gray-200'}`;
        
        const icon = document.createElement('i');
        icon.className = `fa ${achievement.icon} ${achievement.color} ${achievement.achieved ? '' : 'text-gray-400'} text-xl`;
        iconContainer.appendChild(icon);
        
        const title = document.createElement('h4');
        title.className = `text-center font-semibold ${achievement.achieved ? '' : 'text-gray-400'}`;
        title.textContent = achievement.name;
        
        const description = document.createElement('p');
        description.className = `text-center text-sm text-gray-500 ${achievement.achieved ? '' : 'text-gray-400'}`;
        description.textContent = achievement.description;
        
        const status = document.createElement('div');
        status.className = `text-center text-xs mt-2 ${achievement.achieved ? 'text-success' : 'text-gray-400'}`;
        status.textContent = achievement.achieved ? '已达成' : '未达成';
        
        achievementCard.appendChild(iconContainer);
        achievementCard.appendChild(title);
        achievementCard.appendChild(description);
        achievementCard.appendChild(status);
        
        achievementsContainer.appendChild(achievementCard);
      });
    }

    // 更新单词统计
    function updateWordStats() {
      const wordStatsContainer = document.getElementById('word-stats');
      wordStatsContainer.innerHTML = '';
      
      if (words.length === 0) {
        wordStatsContainer.innerHTML = '<div class="text-center text-gray-500 italic">暂无单词数据</div>';
        return;
      }
      
      // 按掌握状态分组
      const mastered = words.filter(word => word.mastered);
      const unmastered = words.filter(word => !word.mastered);
      
      // 创建掌握情况概览
      const overview = document.createElement('div');
      overview.className = 'flex justify-between items-center mb-4 pb-2 border-b';
      
      const totalCount = document.createElement('div');
      totalCount.className = 'font-medium';
      totalCount.innerHTML = `总计: <span class="text-primary">${words.length}</span> 个单词`;
      
      
      const masteredCount = document.createElement('div');
      masteredCount.className = `font-medium ${mastered.length > 0 ? 'text-success' : 'text-gray-400'}`;
      masteredCount.innerHTML = `已掌握: <span>${mastered.length}</span>`;
      
      const unmasteredCount = document.createElement('div');
      unmasteredCount.className = `font-medium ${unmastered.length > 0 ? 'text-warning' : 'text-gray-400'}`;
      unmasteredCount.innerHTML = `未掌握: <span>${unmastered.length}</span>`;
      
      overview.appendChild(totalCount);
      overview.appendChild(masteredCount);
      overview.appendChild(unmasteredCount);
      
      wordStatsContainer.appendChild(overview);
      
      // 显示最近学习的单词
      if (history.length > 0) {
        const recentHeader = document.createElement('h5');
        recentHeader.className = 'font-semibold mb-2 text-gray-700';
        recentHeader.textContent = '最近学习的单词';
        wordStatsContainer.appendChild(recentHeader);
        
        const recentList = document.createElement('div');
        recentList.className = 'space-y-2';
        
        // 取最近学习的5个单词
        const recentWords = history.slice(0, 5).map(item => item.word);
        
        recentWords.forEach(word => {
          const wordItem = document.createElement('div');
          wordItem.className = 'p-2 bg-gray-50 rounded-lg';
          wordItem.textContent = word;
          recentList.appendChild(wordItem);
        });
        
        wordStatsContainer.appendChild(recentList);
      }
      
      // 显示学习进度百分比
      const progressPercentage = Math.round((mastered.length / words.length) * 100);
      
      const progressContainer = document.createElement('div');
      progressContainer.className = 'mt-6';
      
      const progressLabel = document.createElement('div');
      progressLabel.className = 'flex justify-between text-sm mb-1';
      progressLabel.innerHTML = `
        <span class="font-medium">掌握进度</span>
        <span class="text-primary font-bold">${progressPercentage}%</span>
      `;
      
      const progressBar = document.createElement('div');
      progressBar.className = 'w-full bg-gray-200 rounded-full h-2.5';
      
      const progressFill = document.createElement('div');
      progressFill.className = 'bg-primary h-2.5 rounded-full progress-animation';
      progressFill.style.width = `${progressPercentage}%`;
      
      progressBar.appendChild(progressFill);
      progressContainer.appendChild(progressLabel);
      progressContainer.appendChild(progressBar);
      
      wordStatsContainer.appendChild(progressContainer);
    }

    // 更新统计信息
    function updateStats() {
      // 获取今天的日期
      const today = new Date().toISOString().split('T')[0];
      
      // 更新今日学习单词数
      if (!statistics.calendar[today]) {
        statistics.calendar[today] = 0;
      }
      
      // 如果有新学习的单词，更新今日统计
      if (studySession.wordsStudied > 0) {
        statistics.calendar[today] += studySession.wordsStudied;
        statistics.todayWords = statistics.calendar[today];
      }
      
      // 更新连续学习天数
      updateStreak();
      
      // 更新总学习量
      statistics.totalWords = Object.values(statistics.calendar).reduce((sum, count) => sum + count, 0);
      
      // 更新UI显示
      todayStats.textContent = `${statistics.todayWords} 个单词`;
      streakStats.textContent = `${statistics.streak} 天`;
      totalStats.textContent = `${statistics.totalWords} 个单词`;
      
      // 更新日历
      updateCalendar();
    }

    // 更新连续学习天数
    function updateStreak() {
      const today = new Date();
      const yesterday = new Date();
      yesterday.setDate(today.getDate() - 1);
      
      const todayStr = today.toISOString().split('T')[0];
      const yesterdayStr = yesterday.toISOString().split('T')[0];
      
      // 如果今天有学习记录
      if (statistics.calendar[todayStr] > 0) {
        // 如果昨天也有学习记录，连续天数加1
        if (statistics.calendar[yesterdayStr] > 0) {
          statistics.streak++;
        } 
        // 否则重置连续天数为1
        else {
          statistics.streak = 1;
        }
      }
    }

    // 更新日历
    function updateCalendar() {
      const calendarContainer = document.getElementById('calendar-container');
      
      // 如果没有日历数据
      if (Object.keys(statistics.calendar).length === 0) {
        calendarContainer.innerHTML = '<p class="text-gray-500 italic">暂无数据</p>';
        return;
      }
      
      // 获取最近7天的学习数据
      const today = new Date();
      const recentDays = [];
      
      for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(today.getDate() - i);
        const dateStr = date.toISOString().split('T')[0];
        
        recentDays.push({
          date,
          count: statistics.calendar[dateStr] || 0
        });
      }
      
      // 创建日历UI
      const calendarUI = document.createElement('div');
      calendarUI.className = 'grid grid-cols-7 gap-1';
      
      recentDays.forEach(day => {
        const dayElement = document.createElement('div');
        dayElement.className = 'text-center';
        
        // 日期
        const dateElement = document.createElement('div');
        dateElement.className = 'text-xs text-gray-500';
        dateElement.textContent = day.date.getDate();
        
        // 学习量指示
        const countElement = document.createElement('div');
        
        // 设置不同的高度和颜色
        const height = Math.min(day.count * 5, 30); // 最大高度30px
        let bgColor = 'bg-gray-200'; // 默认颜色
        
        if (day.count > 0) {
          bgColor = 'bg-primary';
        }
        
        countElement.className = `mx-auto mt-1 h-${height} w-4 rounded-sm ${bgColor}`;
        
        // 今日标记
        if (day.date.toDateString() === today.toDateString()) {
          dateElement.classList.add('font-bold');
          countElement.classList.add('border-2', 'border-warning');
        }
        
        dayElement.appendChild(dateElement);
        dayElement.appendChild(countElement);
        calendarUI.appendChild(dayElement);
      });
      
      calendarContainer.innerHTML = '';
      calendarContainer.appendChild(calendarUI);
    }

    // 主题切换
    document.getElementById('theme-light').addEventListener('click', () => {
      settings.theme = 'light';
      document.body.classList.remove('bg-gray-900', 'text-white');
      document.body.classList.add('bg-gradient-to-br', 'from-blue-50', 'to-indigo-100');
    });

    document.getElementById('theme-dark').addEventListener('click', () => {
      settings.theme = 'dark';
      document.body.classList.remove('bg-gradient-to-br', 'from-blue-50', 'to-indigo-100');
      document.body.classList.add('bg-gray-900', 'text-white');
    });

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', () => {
      // 加载本地存储的设置
      loadSettings();
      
      // 加载本地存储的单词数据
      loadWords();
      
      // 加载本地存储的统计数据
      loadStatistics();
      
      // 更新统计信息
      updateStats();
    });

    // 保存设置到本地存储
    function saveSettings() {
      localStorage.setItem('vocabulary_game_settings', JSON.stringify(settings));
    }

    // 从本地存储加载设置
    function loadSettings() {
      const savedSettings = localStorage.getItem('vocabulary_game_settings');
      if (savedSettings) {
        settings = JSON.parse(savedSettings);
        
        // 应用主题设置
        if (settings.theme === 'dark') {
          document.body.classList.remove('bg-gradient-to-br', 'from-blue-50', 'to-indigo-100');
          document.body.classList.add('bg-gray-900', 'text-white');
        }
      }
    }

    // 保存单词数据到本地存储
    function saveWords() {
      localStorage.setItem('vocabulary_game_words', JSON.stringify(words));
      localStorage.setItem('vocabulary_game_mastered', JSON.stringify(masteredWords));
    }

    // 从本地存储加载单词数据
    function loadWords() {
      const savedWords = localStorage.getItem('vocabulary_game_words');
      const savedMastered = localStorage.getItem('vocabulary_game_mastered');
      
      if (savedWords && savedMastered) {
        words = JSON.parse(savedWords);
        masteredWords = JSON.parse(savedMastered);
        updateWordCount();
      }
    }

    // 保存统计数据到本地存储
    function saveStatistics() {
      localStorage.setItem('vocabulary_game_stats', JSON.stringify(statistics));
    }

    // 从本地存储加载统计数据
    function loadStatistics() {
      const savedStats = localStorage.getItem('vocabulary_game_stats');
      if (savedStats) {
        statistics = JSON.parse(savedStats);
      }
    }

    // 窗口关闭前保存数据
    window.addEventListener('beforeunload', () => {
      saveSettings();
      saveWords();
      saveStatistics();
    });
  </script>
</body>
</html>